package com.dave.admin.modular.boss.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dave.admin.common.exception.AssertionEx;
import com.dave.admin.component.BossProperties;
import com.dave.admin.modular.boss.dto.UpdateAdminPasswordParam;
import com.dave.admin.modular.boss.dto.UserAdminVo;
import com.dave.admin.modular.boss.entity.UserAdmin;
import com.dave.admin.modular.boss.mapper.UserAdminMapper;
import com.dave.admin.modular.boss.service.IUserAdminService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * BOSS后台用户表 服务实现类
 * </p>
 *
 * @author Dave
 * @since 2024-08-08
 */
@Slf4j
@Service
public class UserAdminServiceImpl extends ServiceImpl<UserAdminMapper, UserAdmin> implements IUserAdminService, InitializingBean {


    private String initPassword;
    private String initAvatar;
    @Autowired
    private BossProperties bossProperties;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public boolean initPassword(String id) {
        UserAdmin userAdmin = new UserAdmin();
        userAdmin.setId(id);
        userAdmin.setPassword(passwordEncoder.encode(initPassword));
        return this.updateById(userAdmin);
    }

    @Override
    public boolean updatePassword(UpdateAdminPasswordParam updatePasswordParam) {
        UserAdmin userAdmin = this.getOne(new QueryWrapper<UserAdmin>().eq(UserAdmin.USERNAME, updatePasswordParam.getUsername()));
        AssertionEx.notNull(userAdmin, "找不到该用户");
        AssertionEx.isTrue(passwordEncoder.matches(userAdmin.getPassword(), updatePasswordParam.getOldPassword()), "旧密码错误");
        userAdmin.setPassword(passwordEncoder.encode(updatePasswordParam.getNewPassword()));
        return this.updateById(userAdmin);
    }

    /**
     * 默认属性- 看配置
     */
    @Override
    public boolean add(UserAdminVo userAdminVo) {
        UserAdmin targetUserAdmin = new UserAdmin();
        BeanUtil.copyProperties(userAdminVo, targetUserAdmin);
        targetUserAdmin.setPassword(passwordEncoder.encode(initPassword));
        targetUserAdmin.setAvatar(initAvatar);
        return this.save(targetUserAdmin);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.initPassword = this.bossProperties.getInitPassword();
        this.initAvatar = this.bossProperties.getInitAvatar();
    }
}

